#include <drv/acpi.h>

#include <mm/page_allocator.h>

static acpi_rsdt_t *rsdt = NULL;
static acpi_xsdt_t *xsdt = NULL;

void acpi_init(void *rsdpv1, void *rsdpv2) {
	if(rsdpv1) {
		acpi_rsdp_t *p = (acpi_rsdp_t *)rsdpv1;

		rsdt = (acpi_rsdt_t *)(uintptr_t)p->rsdt_address;
	}

	if(rsdpv2) {
		acpi_rsdp_t *p = (acpi_rsdp_t *)rsdpv2;

		rsdt = (acpi_rsdt_t *)(uintptr_t)p->rsdt_address;
		xsdt = p->xsdt;
	}

	if(!rsdt && !xsdt) {
		__asm__ volatile("hlt");
	}
}

acpi_table_header_t *acpi_get_table(const char *signature) {
	uint64_t table_count = 0;

	if(xsdt) {
		table_count = (xsdt->header.length - sizeof(acpi_table_header_t)) / sizeof(uintptr_t);

		for(uint64_t i = 0; i < table_count; i++) {
			acpi_table_header_t *table = (acpi_table_header_t *)xsdt->tables[i];

			if(ACPI_COMPARE_SIGNATURE(table->signature, signature)) {
				return table;
			}
		}

		return NULL;
	}

	table_count = (rsdt->header.length - sizeof(acpi_table_header_t)) / sizeof(uint32_t);

	for(uint64_t i = 0; i < table_count; i++) {
		acpi_table_header_t *table = (acpi_table_header_t *)(uintptr_t)rsdt->tables[i];

		if(ACPI_COMPARE_SIGNATURE(table->signature, signature)) {
			return table;
		}
	}

	return NULL;
}
